<?php
// src/Asiah/SiklusBundle/Controller/LinkController.php
namespace Asiah\SiklusBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Asiah\SiklusBundle\Entity\Bookmark;
use Asiah\SiklusBundle\Entity\Link;
use Asiah\SiklusBundle\Entity\Tag;
use Asiah\SiklusBundle\Form\Type\BookmarkType;
use Asiah\SiklusBundle\Model\LinkLogic;

class LinkController extends Controller {

	public function indexAction(Request $request) 
	{
		$url_ses = $this->get('session')->get('url');
		if ($url_ses != null){
			$bukmak = new Bookmark();
			$modelLink = new LinkLogic();
		     $datameta = $modelLink->getMetaData($url_ses); 
			$bukmak->setTitle($datameta['title']);
			$bukmak->setDescription($datameta['description']);
			//$bukmak->setLink($url_ses);
			$form = $this->createForm(new BookmarkType(), $bukmak);

			if($request -> getMethod() == 'POST') {
				$form -> bindRequest($request);
				if($form -> isValid()) {
					$em = $this -> getDoctrine() -> getEntityManager();
					$repoBook = $em -> getRepository('AsiahSiklusBundle:Bookmark');
					$repoTag = $em -> getRepository('AsiahSiklusBundle:Tag');

					$bookmark = $form -> getData();
					$label = $request->request->get('labels');
					$labels = explode (',',$label);
					for ($i=0;$i<count($labels);$i++)
					{
						$tmplabel = $labels[$i];
						$newtag = $repoTag->getOrSaveLabel($tmplabel);	
						$bookmark->addTags($newtag);	
					}
					//echo 'delabel '.$label;
					$usernow = $this->container->get('security.context')->getToken()->getUser();
					$username = $usernow->getUsername();
					$repoBook->saveNewBookmark($bookmark,$username,$url_ses);
					$this->get('session')->set('url',null);
					return $this -> redirect($this -> generateUrl('home'));
				}
			}
			return $this -> render('AsiahSiklusBundle:Link:new.html.twig', array('form' => $form -> createView(), ));
		}
		else
			return $this->redirect($this->generateUrl('home'));
	}
	public function detailAction($url){
		return new Response('ini detail dari url '.$url);
	}
	public function redirectAction($short)
	{
		$em = $this -> getDoctrine() -> getEntityManager();
		$link = $em -> getRepository('AsiahSiklusBundle:Link')->getByShort($short);
		if($link!=null)
			return $this->redirect($link->getRealLink());
		return new Response('ga nemu');
	}

}
